package tech.powerjob.server.web.feign;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import tech.powerjob.common.response.ResultDTO;
import tech.powerjob.server.persistence.remote.model.AppInfoDO;
import tech.powerjob.server.persistence.remote.repository.AppInfoRepository;
import tech.powerjob.server.web.request.ModifyAppInfoRequest;

import javax.annotation.Resource;
import java.util.Date;
import java.util.Optional;

@RestController
@RequestMapping("/feign/appInfo")
public class FeignAppInfoController {
    @Resource
    private AppInfoRepository appInfoRepository;

    @PostMapping("/register")
    public ResultDTO<Void> register(@RequestBody ModifyAppInfoRequest req) {
        String appName = req.getAppName();
        Optional<AppInfoDO> appInfoDO = appInfoRepository.findByAppName(appName);
        // 如果不存在，则保存
        if(!appInfoDO.isPresent()) {
            AppInfoDO newAppInfoDO = new AppInfoDO();
            BeanUtils.copyProperties(req, newAppInfoDO);
            newAppInfoDO.setGmtCreate(new Date());
            appInfoRepository.saveAndFlush(newAppInfoDO);
        }
        return ResultDTO.success(null);
    }

    @GetMapping("/getIdByAppName")
    public ResultDTO<Long> register(String appName) {
        Optional<AppInfoDO> appInfoOpt = appInfoRepository.findByAppName(appName);
        return appInfoOpt.map(appInfoDO -> ResultDTO.success(appInfoDO.getId())).
                orElseGet(() -> ResultDTO.failed(String.format("app(%s)未注册，清注册后使用", appName)));
    }

}
